import { SettingOutlined } from "@ant-design/icons";
import { Form, Input, InputProps, Modal, Tabs, TabsProps } from "antd";
import React, { useEffect, useState } from "react";
import { InterfaceConf } from "./tabs/InterfaceConf";
import {HttpConf} from "./tabs/HttpConf"
interface InterfaceConfSelectorProps {
  value?: ApiConf;
  onChange?: (values: Partial<ApiConf>)=>void;
}
export type ApiMethod = "get" | "post" | "put" | "delete" | "patch";
export interface ApiConf {
  url: string;
  method: ApiMethod;
  dataType?: "json" | "form-data" | "form";
  messages?: {
    success?: string;
    failed?: string;
  };
  headers?: {
    "Content-Type"?: string;
    "Content-Encoding"?: string;
  };
}
export function InterfaceConfSelector(props: InterfaceConfSelectorProps) {
  const [form] = Form.useForm();
  const { value, onChange } = props;
  const [open, setOpen] = useState(false);
  const [url, setUrl] = useState("");
  useEffect(() => {
    setUrl(value?.url || "")
  }, [value]);
  useEffect(() => {
    open && form.setFieldsValue(value);
  }, [open]);
  function handleUrlChange(e: React.ChangeEvent<HTMLInputElement>) {
    const url = e.target.value;
    setUrl(url)
    onChange?.({ ...value, url });
  }

  const items: TabsProps["items"] = [
    {
      key: "1",
      label: "接口设置",
      children: <InterfaceConf/>,
    },
    {
      key: "2",
      label: "HTTP配置",
      children: <HttpConf form={form} rawFormValue={value}/>,
      // forceRender: true,
      // destroyInactiveTabPane: false
    },
    {
      key: "3",
      label: "信息提示",
      children: "Content of Tab Pane 3",
      disabled: true,
    },
  ];
  function handleTabChange(){

  }
  function propsChange(changeValues: Partial<ApiConf>) {
  }

  function handleFinish(values: Partial<ApiConf>){
    const {url} = values
    onChange?.(values)
    setUrl(url as string)
    setOpen(false)
  }
  return (
    <>
      <Input
        addonBefore={value?.method?.toUpperCase() || ""}
        addonAfter={
          <SettingOutlined
            onClick={()=>setOpen(true)}
          />
        }
        value={url}
        title={url}
        onChange={handleUrlChange}
      />
      <Modal
        title="高级设置"
        open={open}
        onCancel={() => {
          setOpen(false);
        }}
        onOk={() => {
          form.submit();
        }}
        destroyOnClose
        width="760px"
      >
        <Form
          form={form}
          onValuesChange={propsChange}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 13 }}
          labelAlign="right"
          labelWrap
          colon={false}
          className="smallText"
          onFinish={handleFinish}
        >
          <Tabs defaultActiveKey="1" items={items} onChange={handleTabChange}/>
        </Form>
      </Modal>
    </>
  );
}
